﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using BBMS.DLL.Base;
using System.IO;
using BBMS.FrontEnd.Constant;

namespace BBMS.DLL.Forms
{
    public partial class frmBackup : Form
    {
        private String databaseName = "";
//         public new static readonly string FunctionKey = "SaoLuuHeThong";
        protected static string GetFunctionKey() { return "SaoLuuHeThong"; }
        public frmBackup()
        {
            InitializeComponent();
            InitConfig();
        }

        private void InitConfig()
        {
           chkBackupType.Items.Clear();
           chkBackupType.Items.Add(new KeyValuePair(".dmp", "File dump"));
           chkBackupType.Items.Add(new KeyValuePair(".sql", "File sql"));
           chkBackupType.SelectedIndex = 0;
           if (System.Configuration.ConfigurationSettings.AppSettings["MySQLDumpPath"] != null)
               txtMySQLDumpPath.Text = System.Configuration.ConfigurationSettings.AppSettings["MySQLDumpPath"].ToString();
           if (System.Configuration.ConfigurationSettings.AppSettings["host"] != null)
               txtHost.Text = System.Configuration.ConfigurationSettings.AppSettings["host"].ToString();
           if (System.Configuration.ConfigurationSettings.AppSettings["uid"] != null)
               txtUid.Text = System.Configuration.ConfigurationSettings.AppSettings["uid"].ToString();
        //   if (System.Configuration.ConfigurationSettings.AppSettings["pwd"] != null)
          //     txtPwd.Text = System.Configuration.ConfigurationSettings.AppSettings["pwd"].ToString();
           if (System.Configuration.ConfigurationSettings.AppSettings["database"] != null)
               databaseName = System.Configuration.ConfigurationSettings.AppSettings["database"].ToString();

        }
        
        private void btnBackup_Click(object sender, EventArgs e)
        {
            if (txtFileName.Text.Trim() == "")
            {
                MessageBox.Show(null, DialogMessage.frmBackupInputBackupFileName, DialogMessage.frmBackupWarning);
                txtFileName.Focus();
                return;
            }

            if (txtMySQLDumpPath.Text.Trim() == "")
            {
                MessageBox.Show(null, DialogMessage.frmBackupInputMySQLDumpPath, DialogMessage.frmBackupWarning);                
                txtMySQLDumpPath.Focus();
                return;
            }

            if (txtHost.Text.Trim() == "")
            {
                MessageBox.Show(null, DialogMessage.frmBackupInputHost, DialogMessage.frmBackupWarning);                
                txtHost.Focus();
                return;
            }

            if (txtUid.Text.Trim() == "")
            {
                MessageBox.Show(null, DialogMessage.frmBackupInputUsername, DialogMessage.frmBackupWarning);
                txtUid.Focus();
                return;
            }

            String result = "";
            result = BackupMySQLDatabase(databaseName, txtMySQLDumpPath.Text.Trim(), txtUid.Text.Trim(), txtPwd.Text.Trim(),txtHost.Text.Trim(), txtFileName.Text.Trim() /* + ((KeyValuePair)chkBackupType.SelectedItem).Key*/);
            if (result == "")
            {
                try
                {
                    FileInfo f = new FileInfo(txtFileName.Text.Trim());
                    if (f.Length != 0)
                        MessageBox.Show(DialogMessage.frmBackupBackupSuccess, DialogMessage.frmBackupInformation);
                    else MessageBox.Show(DialogMessage.frmBackupBackupFail, DialogMessage.frmBackupInformation);
                }
                catch
                {
                    MessageBox.Show(DialogMessage.frmBackupBackupFail, DialogMessage.frmBackupInformation);
                }
            }
            else
            {
                MessageBox.Show(result);
            }


        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenDialog1 = new OpenFileDialog();
            //Tạo bộ lọc các file khi mở OpenDialog
            //Filter lọc ra các file để bạn dễ dàng lựa chọn (ví dụ các fiel MP3, hay WMA,....)
            OpenDialog1.Filter = "Application|*.exe";
            //Tên của hộp thoại hiện lên - Không có thì sẽ là mặc định
            OpenDialog1.Title = "Đường dẫn chương trình sao lưu dữ liệu";
            OpenDialog1.InitialDirectory = @"C:\";
            //Cho phép chọn nhiều file cùng lúc - Mặc định là false
            OpenDialog1.Multiselect = false;
            //Mở hộp thoại
            DialogResult dr = OpenDialog1.ShowDialog();

            //String excelFile = "";
            //excelFile = OpenDialog1.FileName;
            if (dr == DialogResult.OK)
            {
                txtMySQLDumpPath.Text = OpenDialog1.FileName;
            }
            
        }

        public string BackupMySQLDatabase(string databasename, string mysqldumpPath, string username, string password, string host, string outputFile)
        {
            try
            {
                ProcessStartInfo ProcessInfo;
                Process Process;
                ProcessInfo = new ProcessStartInfo("cmd.exe", "/C \"" + mysqldumpPath + "\" -h " + host + " -B " + databasename + " -u " + username + " --password=" + password + " > " + outputFile);
                ProcessInfo.CreateNoWindow = true;
                ProcessInfo.UseShellExecute = false;
                Process = Process.Start(ProcessInfo);
                Process.WaitForExit(20000);
                return "";
            }
            catch
            {
                return DialogMessage.frmBackupBackupError;
            }
        }

        /// <summary&RT;
        /// Author : Himasagar Kutikuppala
        ///A utility method that runs the batch file with supplied arguments.
        /// </summary&RT;
        /// <param name="batchFileName"&RT;Name of the batch file that should be run</param&RT;
        /// <param name="argumentsToBatchFile"&RT;Arguments to the batch file</param&RT;
        /// <returns&RT;Status of running the batch file</returns&RT;
        protected bool ExecuteBatchFile(string batchFileName, string[] argumentsToBatchFile)
        {
            string argumentsString = string.Empty;
            try
            {
                //Add up all arguments as string with space separator between the arguments
                if (argumentsToBatchFile != null)
                {
                    for (int count = 0; count < argumentsToBatchFile.Length; count++)
                    {
                        argumentsString += " ";
                        argumentsString += argumentsToBatchFile[count];
                        //argumentsString += "\"";
                    }
                }

                //Create process start information
                System.Diagnostics.ProcessStartInfo DBProcessStartInfo = new System.Diagnostics.ProcessStartInfo(batchFileName, argumentsString);

                //Redirect the output to standard window
                DBProcessStartInfo.RedirectStandardOutput = true;

                //The output display window need not be falshed onto the front.
                DBProcessStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                DBProcessStartInfo.UseShellExecute = false;

                //Create the process and run it
                System.Diagnostics.Process dbProcess;
                dbProcess = System.Diagnostics.Process.Start(DBProcessStartInfo);

                //Catch the output text from the console so that if error happens, the output text can be logged.
                System.IO.StreamReader standardOutput = dbProcess.StandardOutput;

                /* Wait as long as the DB Backup or Restore or Repair is going on. 
                Ping once in every 2 seconds to check whether process is completed. */
                while (!dbProcess.HasExited)
                    dbProcess.WaitForExit(2000);

                if (dbProcess.HasExited)
                {
                    string consoleOutputText = standardOutput.ReadToEnd();
                    //TODO - log consoleOutputText to the log file.

                }

                return true;
            }

            // Catch all general exceptions
            catch 
            {
                return false;
                //ExceptionManager.Publish(ex);
                //throw new CustomizedException(ARCExceptionManager.ErrorCodeConstants.generalError, ex.Message);
            }
        }

        private void btnBrowse1_Click(object sender, EventArgs e)
        {

            SaveFileDialog SaveDialog1 = new SaveFileDialog();
            //Tạo bộ lọc các file khi mở SaveDialog
            //Filter lọc ra các file để bạn dễ dàng lựa chọn (ví dụ các fiel MP3, hay WMA,....)
            SaveDialog1.Filter = "Dump File|*.dmp|SQL File|*.sql";
            //Tên của hộp thoại hiện lên - Không có thì sẽ là mặc định
            SaveDialog1.Title = "Chọn file backup";
            SaveDialog1.InitialDirectory = @"C:\";
            //Mở hộp thoại
            //Nếu bạn chỉ chọn một file thì giá trị trả về sẽ là một chuỗi kiểu String
            //Vd:
            if (SaveDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = SaveDialog1.FileName;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
